<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px"
      @submit.native.prevent>
      <el-form-item label="巡逻点位" prop="siteName">
        <el-input v-model="queryParams.siteName" placeholder="请输入巡逻点位" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="isShowOperate">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['patrol:site:add']">新增
        </el-button>
      </el-col>
      <!--	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="siteList" @selection-change="handleSelectionChange" style="color: #333333"
      :header-cell-style="{background:'#E3E3E3'}">
      <el-table-column label="巡逻点位" align="center" prop="siteName" />
      <el-table-column label="添加日期" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isShowOperate">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['patrol:site:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['patrol:site:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改巡逻点位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <!-- 搜索框 -->
      <!-- <el-input style="width: 200px;position: absolute;top: 160px;left: 140px;z-index: 999;" v-model="searchInput" placeholder="搜索位置" id="iptId" /> -->
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" @submit.native.prevent
        @keyup.enter.native="submitForm()">
        <el-form-item label="巡逻点位" prop="siteName">
          <el-input v-model="form.siteName" placeholder="请输入巡逻点位" />
        </el-form-item>
        <!-- 高德地图 -->
        <el-form-item label="选择打卡点" prop="longitude">
          <div id="container" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listSite,
    getSite,
    delSite,
    addSite,
    updateSite,
    exportSite
  } from "@/api/patrol/site";
  import {
    checkPermi
  } from "@/utils/permission";
  import AMapLoader from "@amap/amap-jsapi-loader";
  // 设置安全密钥
  window._AMapSecurityConfig = {
    securityJsCode: '47f39bbd3f47b91d1cbb2311453a0b4e',
  }

  export default {
    name: "Site",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 巡逻点位表格数据
        siteList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          siteName: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          siteName: [{
            required: true,
            message: "巡逻点位不能为空",
            trigger: "blur"
          }],
          longitude: [{
            required: true,
            message: "打卡点不能为空",
            trigger: "blur"
          }]
        },
        // 地图相关
        map: null,
        marker: null,
        circle: null,
        radius: 50,
        auto: null,
        placeSearch: null,
        // 地图搜索
        searchInput: ""
      };
    },
    created() {
      this.getList();
      this.getMapRadius();
    },
    computed: {
      isShowOperate: function () {
        return checkPermi(['patrol:site:edit']);
      },
    },
    methods: {
      /** 查询巡逻点位列表 */
      getList() {
        this.loading = true;
        listSite(this.queryParams).then(response => {
          this.siteList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          siteName: null,
          schoolId: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          longitude: null,
          latitude: null
        };
        this.resetForm("form");
        this.searchInput = '';
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加巡逻点位";
        this.initMap()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getSite(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改巡逻点位";
          this.initMap(this.form.longitude, this.form.latitude);
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateSite(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addSite(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.resetQuery();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除所选数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          type: "warning"
        }).then(function () {
          return delSite(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有巡逻点位数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          type: "warning"
        }).then(function () {
          return exportSite(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      initMap(lng, lat) {
        AMapLoader.load({
          "key": "a423874b07f076758138f4d36f6f74df",
          "version": "2.0",
          "plugins": [
            "AMap.Scale",
            "AMap.HawkEye",
            'AMap.MapType',
            // "AMap.AutoComplete",
            // "AMap.PlaceSearch"
          ]
        }).then((AMap) => {
          // 初始化地图
          this.map = new AMap.Map('container', {
            viewMode: "2D",
            zoom: 13,
            // 江北区人民政府
            center: [106.580323, 29.612549],
            resizeEnable: true
          });
          if (lng && lat) {
            this.map.setCenter([lng, lat], false, 100);
            this.marker = new AMap.Marker({
              position: [lng, lat]
            });
            this.circle = new AMap.Circle({
              center: [lng, lat],
              radius: this.radius, //半径
              borderWeight: 3,
              strokeColor: "#FF33FF",
              strokeOpacity: 1,
              strokeWeight: 6,
              strokeOpacity: 0.2,
              fillOpacity: 0.4,
              strokeDasharray: [10, 10],
              fillColor: '#1791fc',
              zIndex: 50,
              bubble: true
            })
            this.map.add(this.marker);
            this.map.add(this.circle);
          }

          this.map.addControl(new AMap.MapType({defaultType: 1}));
          this.map.addControl(new AMap.Scale());
          this.map.addControl(new AMap.HawkEye({
            isOpen: true
          }));
          this.map.on('click', this.addMarker);
          // this.searchMap();
        }).catch(e => {
          console.log(e);
        });
      },
      // 关键字查询
      searchMap() {
        this.auto = new AMap.AutoComplete({
          input: "iptId"
        });
        this.placeSearch = new AMap.PlaceSearch({
          map: this.map
        });
        this.auto.on("select", this.selectSite);
      },
      //当选中某条搜索记录时触发
      selectSite(e) {
        this.lnglat = [e.poi.location.lng, e.poi.location.lat];
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name);
      },
      // 添加标记
      addMarker(e) {
        if (this.marker) {
          this.map.remove(this.marker);
          this.map.remove(this.circle);
        }
        this.marker = new AMap.Marker({
          position: [e.lnglat.getLng(), e.lnglat.getLat()]
        });
        this.circle = new AMap.Circle({
          center: [e.lnglat.getLng(), e.lnglat.getLat()],
          radius: this.radius, //半径
          borderWeight: 3,
          strokeColor: "#FF33FF",
          strokeOpacity: 1,
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillOpacity: 0.4,
          strokeDasharray: [10, 10],
          fillColor: '#1791fc',
          zIndex: 50,
          bubble: true
        })
        this.map.add(this.marker);
        this.map.add(this.circle);
        this.form.longitude = e.lnglat.getLng();
        this.form.latitude = e.lnglat.getLat();
        this.$refs["form"].clearValidate("longitude");
      },
      getMapRadius() {
        this.getDicts("clocking_radius").then(response => {
          this.radius = response.data[0].dictValue;
        });
      }
    }
  };

</script>

<style scoped>
  #container {
    overflow: hidden;
    width: 660px;
    height: 400px;
    margin: 0;
    font-family: "微软雅黑";
  }

</style>
<style>
  /* 隐藏高德logo  */
  .amap-logo {
    display: none !important;
  }

  /* 隐藏高德版权  */
  .amap-copyright {
    display: none !important;
  }

  /* 高德搜索栏层级 */
  .amap-sug-result {
    z-index: 2999 !important;
  }

  /* 隐藏高德地图路况切换 */
  .amap-ctrl-overlay-layer {
    display: none !important;
  }

</style>
